package cn.ichiva.dl.tushare.common;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * Created by game group on 2020/12/14.
 */
public class MailHelper {

    public static Session getSession(String userName,String password){
        Properties properties = getMailProperties();
        return Session.getDefaultInstance(properties,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName,password);
            }
        });
    }

    private static Properties getMailProperties() {
        try {
            Properties properties = System.getProperties();
            String host = "smtp.qq.com";
            properties.setProperty("mail.smtp.host", host);
            properties.put("mail.smtp.auth", "true");
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
            return properties;
        }catch (GeneralSecurityException e){
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String to = "874460517@qq.com";
        String from = "951513793@qq.com";
        Session session = getSession("951513793@qq.com", "xtbbkqjpzjjqbfea");

        try{
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("test!");
            message.setText("This is a test message");
            Transport.send(message);
            System.out.println("Sent message successfully....");
        }catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}
